<template>
  <Transition name="fade">
    <div class="x_drawer_mask" v-if="modelValue" @click="handleClose">
      <Transition name="slide">
        <div class="x_drawer" :class="positionClass" @click.stop>
          <div class="x_drawer_header">
            <h3>{{ title }}</h3>
            <button class="x_drawer_close" @click="handleClose">×</button>
          </div>
          <div class="x_drawer_content">
            <slot></slot>
          </div>
        </div>
      </Transition>
    </div>
  </Transition>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  title: {
    type: String,
    default: ''
  },
  position: {
    type: String,
    default: 'right'
  }
})

const emit = defineEmits(['update:modelValue'])

const positionClass = computed(() => {
  return `x_drawer_${props.position}`
})

const handleClose = () => {
  emit('update:modelValue', false)
}

// 处理 ESC 键关闭
const handleEsc = (e: KeyboardEvent) => {
  if (e.key === 'Escape' && props.modelValue) {
    handleClose()
  }
}

// 处理滚动锁定
const lockScroll = () => {
  if (props.modelValue) {
    document.body.style.overflow = 'hidden'
  } else {
    document.body.style.overflow = ''
  }
}

onMounted(() => {
  window.addEventListener('keydown', handleEsc)
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleEsc)
  document.body.style.overflow = ''
})

// 监听 modelValue 变化来锁定滚动
watch(() => props.modelValue, lockScroll, { immediate: true })
</script>

<style scoped>
.x_drawer_mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}

.x_drawer {
  position: fixed;
  background: white;
  height: 100%;
  width: 80%;
  max-width: 300px;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
}

.x_drawer_right {
  right: 0;
  top: 0;
}

.x_drawer_header {
  padding: 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.x_drawer_header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.x_drawer_close {
  border: none;
  background: none;
  font-size: 24px;
  cursor: pointer;
  padding: 4px;
  color: #999;
  transition: color 0.3s;
}

.x_drawer_close:hover {
  color: #333;
}

.x_drawer_content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

/* 遮罩层动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 抽屉滑动动画 */
.slide-enter-active,
.slide-leave-active {
  transition: transform 0.3s ease;
}

.slide-enter-from,
.slide-leave-to {
  transform: translateX(100%);
}
</style> 